package com.iss.card.view.account;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.iss.card.CardActivity;
import com.iss.card.CardController;
import com.iss.card.R;
import com.iss.card.CardController.EventType;
import com.iss.card.common.ApplicationManager;
import com.iss.card.common.FunctionUtil;
import com.iss.card.common.IBackKeyListener;
import com.iss.card.common.Tools;
import com.iss.card.model.UserInfo;
import com.iss.card.view.model.ResponseBean;
import com.iss.card.webservice.WebServiceAsyncService;
import com.iss.card.webservice.WebServiceAsyncService.Operation;
import com.iss.card.webservice.WebServiceAsyncService.PostExecute;
import com.iss.card.webservice.WebServiceAsyncServiceHelper;
import com.iss.card.webservice.WebServiceManager.WebServiceRegistrationParameter;
import com.iss.card.webservice.WebServiceManager.WebServiceUrlPortManager;
import com.iss.card.webservice.WebServiceUtils;

public class AccountLogInFragment extends Fragment implements OnClickListener,
		IBackKeyListener, OnFocusChangeListener {

	private final static String TAG = AccountLogInFragment.class
			.getSimpleName();
	private Activity mContext;
	private Button btnLonin, btnRegisterButton;
	private EditText edtUsermobile, edtPassword;
	private Button btnBack;
	private ImageButton btnForget;
	private ContentValues mValues;
	private ArrayList<UserInfo> accountList;
	private UserInfo accountBean;
	private CheckBox chkBoxautoLogin;
	private OnLoginButtonCLick onLoginButtonCLick;

	private void initView(LinearLayout layout) {
		Log.d(TAG, "initView");
		btnLonin = (Button) layout.findViewById(R.id.login_btn_login);
		btnRegisterButton = (Button) layout
				.findViewById(R.id.login_btn_register);
		btnBack = (Button) layout.findViewById(R.id.return_button);
		btnBack.setVisibility(View.VISIBLE);
		btnForget = (ImageButton) layout.findViewById(R.id.job_button);
		btnForget.setBackgroundResource(R.drawable.forgetpass_selector);
		
		btnForget.setVisibility(View.VISIBLE);
		((TextView) layout.findViewById(R.id.job_name_val))
				.setText(R.string.title_user_login);
		chkBoxautoLogin = (CheckBox) layout
				.findViewById(R.id.account_auto_login);

		edtUsermobile = (EditText) layout.findViewById(R.id.login_user_mobile);
		edtPassword = (EditText) layout.findViewById(R.id.lonin_user_password);
		edtPassword.setOnFocusChangeListener(this);
		btnLonin.setOnClickListener(this);
		btnBack.setOnClickListener(this);
		btnForget.setOnClickListener(this);
		btnRegisterButton.setOnClickListener(this);

	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mContext = activity;
		onLoginButtonCLick = (OnLoginButtonCLick) mContext;

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		if(getArguments().getString(ApplicationManager.KEY_LOGIN_FRAG_FIRED_BY)!= null &&
				getArguments().getString(ApplicationManager.KEY_LOGIN_FRAG_FIRED_BY)
				.equals(ApplicationManager.LOGIN_FROM_MYCARD)){
			ApplicationManager.LAST_VIEW_FROM_MAIN = 
					ApplicationManager.LOGIN_FROM_MYCARD;
		}else {
			ApplicationManager.LAST_VIEW_FROM_MAIN = "";
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		LinearLayout layout = (LinearLayout) inflater.inflate(
				R.layout.account_frag_login, null);
		initView(layout);
		return layout;
	}

	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		super.onDetach();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.login_btn_login:
			doLogin();
			break;

		case R.id.login_btn_register:

			onLoginButtonCLick.onRegister();
			break;
		case R.id.return_button:

			mContext.finish();
			break;
		case R.id.job_button:

			onLoginButtonCLick.onForgetPassword();
			break;

		default:
			break;
		}
	}

	/*
	 * ��¼
	 */
	private void doLogin() {
		String userNameVal = edtUsermobile.getText().toString();
		String passwordVal = edtPassword.getText().toString();

		if (TextUtils.isEmpty(userNameVal)) {
			Tools.showToast(mContext, R.string.user_name_not_null);
			return;
		}

		if (TextUtils.isEmpty(passwordVal)) {
			Tools.showToast(mContext, R.string.password_not_null);
			return;
		}

		String[] obj = { userNameVal, passwordVal };

		doAsyncService(obj);
	}

	private void doAsyncService(String[] obj) {

		if (obj == null) {
			Log.e(TAG, "obj is null");
			return;
		}

		WebServiceAsyncService asyncService = new WebServiceAsyncService();
		asyncService.setParameterToAsyncService(mContext,
				asyncService.getNextToken(),
				Operation.OP_SERVICE_ARG_ACCOUNT_LOGIN,
				WebServiceRegistrationParameter.PRODUCT_ACCOUNT_LOGIN, obj,
				WebServiceUrlPortManager.ACTION_URL_PORT_ACCOUNT_LOGIN, this,
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		asyncService.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token, Object envelope,
					int index) {
				JSONObject mAccountObj = getAccountobject();
				if (envelope == null) {
					Log.e(TAG, "envelope is null");
					return;
				}
				ResponseBean response = WebServiceUtils
						.getObjectResultToBaseInfo(envelope, UserInfo.class);
				accountList = (ArrayList<UserInfo>) response.getReturnList();
				if (response.getStatus().equals(
						ApplicationManager.RESPONSE_OK)) {
					Toast.makeText(mContext, R.string.login_successful,
							Toast.LENGTH_SHORT).show();

				} else {
					Tools.showToast(mContext, response.getMessage());
					edtPassword.setText("");
					return;
				}

				/*if (accountList.size() > 0) {
					FunctionUtil.saveCurrentLogInUser((UserInfo) accountList
							.get(0));
					accountBean = accountList.get(0);
				}*/
				for (UserInfo info : accountList){
					accountBean = info;
					break;
				}
				FunctionUtil.saveCurrentLogInUser(accountBean);
				
				if (chkBoxautoLogin.isChecked()) {
					if (mAccountObj.has(edtUsermobile.getText().toString())) {

						mAccountObj.remove(edtUsermobile.getText().toString());

						try {
							mAccountObj.put(edtUsermobile.getText().toString(),
									edtPassword.getText().toString());
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					} else {

						try {
							mAccountObj.put(edtUsermobile.getText().toString(),
									edtPassword.getText().toString());
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

				} else {
					if (mAccountObj.has(edtUsermobile.getText().toString())) {
						mAccountObj.remove(edtUsermobile.getText().toString());
					}
				}
				setAccountObject(mAccountObj);
				FunctionUtil.saveCurrentLogInUser(accountBean);
				mContext.finish();
			}
		});
	}

	@Override
	public void cancelUpdate(Object... params) {
		// TODO Auto-generated method stub

	}

	public interface OnLoginButtonCLick {
		public void onRegister();

		public void onForgetPassword();
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub
		String usrMobile = edtUsermobile.getText().toString();
		JSONObject mAccountObj = getAccountobject();
		if (v == edtPassword && v.isFocused() && mAccountObj != null) {
			if (usrMobile != null && mAccountObj.has(usrMobile)) {
				try {
					edtPassword.setText("");
					edtPassword.setText(mAccountObj.getString(usrMobile));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					Log.e(TAG, "JSONObject error ===> " + e.toString());
					e.printStackTrace();
				}
			}
		}
	}
	
	
	private JSONObject getAccountobject(){
		JSONObject accountObj = new JSONObject();
		try {
			if (!TextUtils.isEmpty(FunctionUtil.getUsrInfoForAutoLogin())) {
				accountObj = new JSONObject(
						FunctionUtil.getUsrInfoForAutoLogin());
			} 
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Log.e(TAG, "accountObj Error ===> " + e.toString());
			e.printStackTrace();
		}
		
		return accountObj;
	}
	
	private void setAccountObject(JSONObject account){
		FunctionUtil.saveUsrInfoForAutoLogin(account.toString());
		
	}
}
